<template>
  <nav class="navbar">
    <div class="container">
      <div class="logo">
        <router-link to="/">Blog</router-link>
      </div>
      <div class="menu">
        <ul>
          <li><router-link to="/">Home</router-link></li>
          <li><router-link to="/articles">Articles</router-link></li>
          <li><router-link to="/categories">Categories</router-link></li>
          <li v-if="!isLoggedIn"><router-link to="/login">Login</router-link></li>
          <li v-if="!isLoggedIn"><router-link to="/register">Register</router-link></li>
          <li v-if="isLoggedIn" class="user-menu">
            <span>{{ currentUser.username }}</span>
            <ul class="dropdown">
              <li><router-link to="/profile">Profile</router-link></li>
              <li><router-link to="/dashboard">Dashboard</router-link></li>
              <li><button @click="logout">Logout</button></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { useUserStore } from '../store/userStore';
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';

const userStore = useUserStore();
const router = useRouter();
const isLoggedIn = userStore.isAuthenticated;
const currentUser = userStore.currentUser;

onMounted(() => {
  userStore.fetchUserInfo();
});

const logout = () => {
  userStore.logout();
  router.push('/login');
};
</script>

<style scoped>
.navbar {
  background-color: #333;
  color: white;
  padding: 1rem 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo a {
  color: white;
  text-decoration: none;
  font-size: 1.5rem;
  font-weight: bold;
}

.menu ul {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.menu li {
  margin-left: 1.5rem;
  position: relative;
}

.menu a {
  color: white;
  text-decoration: none;
}

.menu a:hover {
  text-decoration: underline;
}

.user-menu {
  cursor: pointer;
}

.dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: #333;
  padding: 0.5rem 0;
  min-width: 150px;
  display: none;
}

.user-menu:hover .dropdown {
  display: block;
}

.dropdown li {
  margin: 0;
  padding: 0.5rem 1rem;
}

.dropdown button {
  background: none;
  color: white;
  border: none;
  padding: 0;
  font: inherit;
  cursor: pointer;
  text-decoration: none;
}

.dropdown button:hover {
  text-decoration: underline;
}
</style>